import {
  ds
} from '../../../tools/data'
import {
  users
} from '../../../tools/users'
import {
  localData
} from '../../../tools/localData'
import {
  checkTool
} from '../../../tools/check'
import {
  ui
} from '../../../tools/ui'
import {
  pages
} from '../../../tools/pages'
import {
  dsFiles
} from '../../../tools/dsFiles'
import {
  dsx
} from '../../../tools/datax'

const cloudPrefix = getApp().globalData.cloudPrefix

Page({
  data: {
    userInfo: {}, // user
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
    cloudPrefix,
    replyList: [],
    setting: {}
  },
  onLoad() {
    const that = this
    that.init()
  },
  init() {
    this.fetchData()
    this.loadSetting()
  },
  async loadSetting() {
    const _ = dsx.cmd
    const res = await dsx.coll('setting').where({
        _id: _.exists(true)
      })
      .limit(1)
      .get()
    const setting = res.data[0]
    this.setData({
      setting
    })
  },
  async updateSetting() {
    ui.loading()
    const {
      setting
    } = this.data
    setting.notify.unreadMsg = Number(setting.notify.unreadMsg)
    setting.notify.refound = Number(setting.notify.refound)
    setting.notify.newOrder = Number(setting.notify.newOrder)
    await dsx.cloudUpdate('setting', setting._id, setting).then(res => {
      ui.loading(false)
      ui.toast(res.result.errMsg.endsWith(':ok'))
      // console.log(res)
    })
  },
  async fetchData() {
    ui.loading()
    const that = this
    users.getUserInfo()
      .then(async userInfo => {
        that.updateUserInfo(userInfo)
        ui.loading(false)
        // console.log(userInfo)
      })
  },
  updateUserInfo(userInfo) {
    if (!userInfo._id) return
    this.setData({
      userInfo
    })
  },
  onRefresh() {
    const that = this
    ui.loading()
    ds.cloudGetByOpenid('users', res => {
      const userInfo = res.result.data[0]
      if (userInfo) that.updateUserInfo(userInfo)
      ui.loading(false)
    })
  },
  saveSettingTap() {
    const {
      notify
    } = this.data.setting
    const fn = (val) => checkTool.test(val, checkTool.CommonRegex.integer) && Number(val) > 0
    checkTool.check([{
      value: notify.unreadMsg,
      title: '客服消息',
      fn
    }, {
      value: notify.newOrder,
      title: '新的订单',
      fn
    }, {
      value: notify.refound,
      title: '退款申请',
      fn
    }])
    this.updateSetting()
  },
  async onBackTap() {
    if (!await ui.confirmx('确定返回吗？')) return
    wx.navigateBack()
  },
  fastReplyCallback(reply, options) {
    // console.log(reply, options)
    const {
      setting
    } = this.data
    const replyList = setting.fastReply?.list || []
    replyList.push(reply)
    setting.fastReply.list = replyList
    this.setData({
      setting
    })
  },
  saveUserInfo(userInfo, cb) {
    if (!userInfo._id) return
    ds.cloudUpdate('users', userInfo._id, userInfo, res => {
      if (cb) cb(res)
    })
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;

    switch (dataset.type) {
      case 'gender':
        ui.actionSheet(['男', '女', '保密'], res => {
          let userInfo = dataset.userinfo
          userInfo.personInfo = userInfo.personInfo || {}
          userInfo.personInfo.gender = res
          this.updateUserInfo(userInfo)
        })
        break;
      default: {
        break;
      }
    }
  },
  onValueChange(e) {
    const {
      setting
    } = this.data
    const name = ui.eventData(e, 'name')
    const {
      value
    } = e.detail
    setting.notify[name] = value
    this.setData({
      setting
    })
  },
  getPhoneNumber(event) {
    const userInfo = event.currentTarget.dataset.userinfo
    users.getMobile(event, phoneNumber => {
      userInfo.phoneNumber = phoneNumber
      this.updateUserInfo(userInfo)
    })
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },
  async toModifyAvatar() {
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      Toast({
        context: this,
        selector: '#t-toast',
        message: `已选择图片-${tempFileName}`,
        theme: 'success',
      });
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'fail',
      });
    }
  },
  deliFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/deliFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  },
  deductFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deductFee/deductFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  },
  onAddReplyTap() {
    wx.navigateTo({
      url: '/pages/chat/fast-reply/fast-reply?action=new',
    })
  },
  async onDeleteReplyTap(e) {
    if (!await ui.confirmx('确定删除吗？')) return
    const index = ui.eventData(e, 'index')
    const {
      setting
    } = this.data
    const replyList = setting.fastReply?.list
    replyList.splice(index, 1)
    this.setData({
      setting
    })
  },
  onEditReplyTap() {
    // console.log('edit')
  }

});